#pragma once
#include <iostream>
#include <string>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
//#include<string.h>

const std::string gpath = "/home/lhx/112";

int gprojid = 0x6666;

int gshmsize = 4096;

mode_t gmode = 0600;

std::string ToHex(key_t k) {
  char buffer[64];
  snprintf(buffer, sizeof(buffer), "0x%x", k);
  return buffer;
}


    
//1.创建key，保证看到同一份内存的标识 _key = ::ftok(gpath.c_str(), gprojid);
//2.通过key创建共享内存 && 获取共享内存_shmid = ::shmget( _key, gshmsize, shmflg);
//3.将共享内存挂接到自己的地址空间
//4.去关联，解除用户地址与共享内存间的映射联系
//删除共享内存
class ShareMemory 
{
private:
  void CreatShmHelper(int shmflg) 
  {
    _key = ::ftok(gpath.c_str(), gprojid);
    if ( _key < 0) 
    {
      std::cerr << "ftok error" << std::endl;
      return;
    }
    //std::cout << "k : " << ToHex(k) << std::endl;

    _shmid = ::shmget( _key, gshmsize, shmflg);
    if ( _shmid < 0) 
    {
      std::cerr << "shmget error" << std::endl;
      return;
    }
    std::cout << "shmid : " <<  _shmid << std::endl;
  }

public:
  ShareMemory() :_shmid(-1),_key(0),_addr(nullptr)
  {}
  ~ShareMemory() {}
  void CreatShm() 
  {
    if(_shmid == -1)
     CreatShmHelper(IPC_CREAT | IPC_EXCL | gmode);
  }


  void GetShm() 
  {
    CreatShmHelper(IPC_CREAT);
  }


  void AttachShm() 
  {
    _addr = ::shmat(_shmid,nullptr,0);
    if((long long)_addr == -1)
    {
        return;
    }
    //std::cout << "attach done" << std::endl;
    return;
  }


  void DetachShm() 
  {
    if(_addr != nullptr)
    ::shmdt(_addr);
    //std::cout << "detach done" << std::endl;
  }

  void DeleteShm()
  {
    ::shmctl(_shmid,IPC_RMID,nullptr);
    //std::cout << "delete done" << std::endl;
  }


  void* GetAddr()
  {
    return _addr;
  }
  void ShmMeta() 
  {

  }

private:
    int _shmid;
    key_t _key;
    void* _addr;
};
ShareMemory shm;

struct data
{
    char status[32];
    char lasttime[48];
    char image[4000];
};